package com.ruoyi.common.aliyun;

import com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenRequest;
import com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenResponse;
import com.aliyun.dingtalktodo_1_0.models.*;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import lombok.SneakyThrows;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@UtilityClass
public class DingdingApi {
    public final String APPKEY = "dingw3ugw0tlpgxf0ntl";
    public final String APPSECRET = "UpcOE4xxCzVuUArtu65YyZ9ax3YcMdE-1bo2lxajYbSVgGeHaxyl2JBAlKpJ06Ru";
    public final String AESKEY = "8u2SSPF6cRN4BwHXodZCrZ6t1G9TdgaiyOTm9zjEuAD";
    public final String AESTOKEN = "ZQWGMXHdDEH0GxYoAz6siL1l56thvF4GPVIpw33UAAcVcpmlh";
    public final String creatorId = "60fSu66fPz1NZqJr2l2gtgiEiE";


    private final String ACCESS_TOKEN_KEY = "dingding:accessToken";

    private com.aliyun.dingtalktodo_1_0.Client client_todo;
    private com.aliyun.dingtalkoauth2_1_0.Client client_oauth;

    static {
        Config config = new Config();
        config.protocol = "https";
        config.regionId = "central";
        try {
            client_todo = new com.aliyun.dingtalktodo_1_0.Client(config);
            client_oauth = new com.aliyun.dingtalkoauth2_1_0.Client(config);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void overTask(String taskId){
        UpdateTodoTaskHeaders updateTodoTaskHeaders = new UpdateTodoTaskHeaders();
        updateTodoTaskHeaders.xAcsDingtalkAccessToken = getAccessToken();
        UpdateTodoTaskRequest updateTodoTaskRequest = new UpdateTodoTaskRequest()
                .setDone(true);
        try {
            client_todo.updateTodoTaskWithOptions(creatorId, taskId, updateTodoTaskRequest, updateTodoTaskHeaders, new RuntimeOptions());
        }  catch (TeaException err) {
            log.error("createTodoTask err", err);
            throw new ServiceException(err.message);
        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            log.error("createTodoTask err", err);
            throw new ServiceException(err.message);
        }
    }

    public CreateTodoTaskResponseBody createTask(String subject, String desc, List<String> executorIds) {
        CreateTodoTaskHeaders createTodoTaskHeaders = new CreateTodoTaskHeaders();
        createTodoTaskHeaders.xAcsDingtalkAccessToken = getAccessToken();
        CreateTodoTaskRequest.CreateTodoTaskRequestDetailUrl detailUrl = new CreateTodoTaskRequest.CreateTodoTaskRequestDetailUrl()
                .setPcUrl("http://localhost/light/light_list");
        CreateTodoTaskRequest createTodoTaskRequest = new CreateTodoTaskRequest()
                .setCreatorId(creatorId)
                .setExecutorIds(executorIds)
                .setSubject(subject)
                .setDescription(desc)
                .setDetailUrl(detailUrl)
                .setNotifyConfigs(new CreateTodoTaskRequest.CreateTodoTaskRequestNotifyConfigs().setDingNotify("1"));
        try {
            CreateTodoTaskResponse task = client_todo.createTodoTaskWithOptions(creatorId, createTodoTaskRequest, createTodoTaskHeaders, new RuntimeOptions());
            return task.getBody();
        } catch (TeaException err) {
            log.error("createTodoTask err", err);
            throw new ServiceException(err.message);
        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            log.error("createTodoTask err", err);
            throw new ServiceException(err.message);
        }
    }

    @SneakyThrows
    public String getAccessToken() {
        String accessToken = SpringUtils.getBean(RedisCache.class).getCacheObject(ACCESS_TOKEN_KEY);
        if (StringUtils.isNotBlank(accessToken)) {
            return accessToken;
        }
        return getAndRefreshAccessToken();
    }

    private synchronized String getAndRefreshAccessToken() throws Exception {
        String accessToken = SpringUtils.getBean(RedisCache.class).getCacheObject(ACCESS_TOKEN_KEY);
        if (StringUtils.isNotBlank(accessToken)) {
            return accessToken;
        }
        GetAccessTokenRequest request = new GetAccessTokenRequest();
        request.setAppKey(APPKEY);
        request.setAppSecret(APPSECRET);
        GetAccessTokenResponse response = client_oauth.getAccessToken(request);
        accessToken = response.getBody().getAccessToken();
        SpringUtils.getBean(RedisCache.class).setCacheObject(ACCESS_TOKEN_KEY, accessToken, response.getBody().getExpireIn().intValue(), TimeUnit.SECONDS);
        return accessToken;
    }


}
